import type { AxiosInstance, AxiosResponse, AxiosError } from 'axios'
import { useUserStore } from '@/store/modules/user'

export const setupResponse = (http: AxiosInstance) => {
  http.interceptors.response.use(
    (response: AxiosResponse) => {
      const { data } = response
      const { success, message } = data
      if (success) {
        return data
      } else {
        return Promise.reject(message)
      }
    },
    (error: AxiosError) => {
      const msg: string[] = []
      // HTTP 状态码
      const status: number = error.response?.status ?? 0
      const message: string = (error.response?.data as R)?.message || ''
      switch (status) {
        case 400:
          message.split(';').forEach((item) => {
            const errItem = item.substring(item.indexOf(':') + 1)
            errItem && msg.push(errItem)
          })
          break
        case 401:
          msg.push('token失效，请重新登录')
          // 这里可以触发退出的 action
          console.log('请重新登录')
          useUserStore().doLogout(false)
          break
        case 403:
          msg.push('没有权限,请获取权限后登录')
          break
        case 404:
          msg.push('资源走丢了')
          break
        case 500:
          msg.push(message ?? '服务器故障')
          break
        case 502:
          msg.push('数据库查询错误')
          break
        default:
          msg.push(message ?? '网络连接错误')
      }
      if (msg && msg.length > 0) {
        msg.forEach((item: string) => {
          window.$message.error(item)
        })
      } else {
        window.$message.error(error.message)
      }
      // window.$message.error(message || msg || error.message)
      return Promise.reject(message ? new Error(message) : error)
    }
  )
}
